package xyz.xiaoshengfu.xrpc.main;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import xyz.xiaoshengfu.xrpc.common.JsonUtils;
import xyz.xiaoshengfu.xrpc.consumer.XRpcConsumerSubscribeClient;
import xyz.xiaoshengfu.xrpc.data.XRpcResources;
import xyz.xiaoshengfu.xrpc.provider.XRpcProviderRegisterClient;
import xyz.xiaoshengfu.xrpc.provider.XRpcProviderServer;

/**
 * <p>Title: XRpcMainApplication</p>
 * <p>Description: xRPC主启动应用</p>
 * @author xiaoshengfu(2439323118@qq.com)
 * @date 2020年3月24日
 */
public class XRpcMainApplication {

	private XRpcConsumerSubscribeClient xRpcConsumerSubscribeClient;
	private XRpcProviderRegisterClient xRpcProviderRegisterClient;

	public XRpcMainApplication() {
		super();
	}

	public void start() {
		XRpcResources.xRpcConfig.setStartUpTime(new Date());
		registerXRpcApplication();
		if (XRpcResources.xRpcConfig.getReferenceBeanList().size() > 0) {
			xRpcConsumerSubscribeClient = new XRpcConsumerSubscribeClient();
			xRpcConsumerSubscribeClient.consumerFirstSubscribe();
		}
		if (XRpcResources.xRpcConfig.getProtocolConfig() != null
				&& XRpcResources.xRpcConfig.getServiceBeanList().size() > 0) {
			new Thread(() -> {
				new XRpcProviderServer().run();
			}).start();
			xRpcProviderRegisterClient = new XRpcProviderRegisterClient();
			xRpcProviderRegisterClient.providerScheduledRegister();
		}

	}

	private void registerXRpcApplication() {
		Executors.newScheduledThreadPool(1).scheduleWithFixedDelay(() -> {
			XRpcResources.jedisClientPool.setex(
					"xRpcConfig:" + XRpcResources.xRpcConfig.getApplicationConfig().getName(), 180,
					JsonUtils.objectToJson(XRpcResources.xRpcConfig));
		}, 0L, 120L, TimeUnit.SECONDS);
	}
}
